package com.factory.socket;

import com.factory.utils.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Author: dongyaoyao
 * @CreateTime: 2025-04-09
 * @Description:
 * @Version: 1.0
 */
public class MessageDecoder {
    private  final Logger log = LoggerFactory.getLogger(MessageDecoder.class);
    public  List<String> dealBody(String Data) {
        List<String> datas = new ArrayList<>();
        for (int i = 0; i < Data.length(); i += 8) {
            int endIndex = Math.min(i + 8, Data.length());
            String chunk = Data.substring(i, endIndex);
            datas.add(parseBitsFloat(chunk)+"");
        }
        return datas;
    }

    public List<String> dealBodyOpen(String bytes) {
        List<String> datas = new LinkedList<>();
        for (int i = 0; i < bytes.length(); i += 2) {
            int endIndex = Math.min(i + 2, bytes.length());
            String chunk = bytes.substring(i, endIndex);
            datas.add(chunk);
        }
        return datas;
    }

    /**
     * 字节转换为 十进制数字
     */
    private int parseIntDataBytes(byte[] data, int startIndex, int length) {
        return this.parseIntDataBytes(data, startIndex, length, 0);
    }

    /**
     * 字节转换为 有符号十进制数字
     */
    private int parseIntDataBytes(byte[] data, int startIndex, int length, int defaultVal) {
        try {
            // 字节数大于4,从起始索引开始向后处理4个字节,其余超出部分丢弃
            final int len = Math.min(length, 4);
            byte[] tmp = new byte[len];
            System.arraycopy(data, startIndex, tmp, 0, len);
            return Integer.valueOf(HexUtil.byteArrayToHexString(tmp), 16).shortValue();
        } catch (Exception e) {
            log.error("解析整数出错:{}", e.getMessage());
            e.printStackTrace();
            return defaultVal;
        }
    }

    private float parseBitsFloat(String bitData) {
        // 方法 1：使用 Long.parseLong，然后强转为 int（适用于32位十六进制）
        long longBits = Long.parseLong(bitData, 16);
        int intBits = (int) longBits; // 直接强制转换
        return Float.intBitsToFloat(intBits);
    }

    public  List<String> concatArrays(List<String> arr1, List<String> arr2) {
        List<String> combined = Stream.concat(arr1.stream(), arr2.stream())
                .collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
        return combined;
    }
}
